package cn.zhaoyuening.zhaocloud.provider.handler.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import cn.zhaoyuening.zhaocloud.provider.handler.CloudServiceHandler;

/**
 * 与Spring IOC容器结合的CloudServiceHandler实现 获取服务的描述信息 从IOC容器中获取服务 调用并返回结果
 * 
 * @author 赵岳宁
 *
 */
public class SpringCloudServiceHandler implements CloudServiceHandler, ApplicationContextAware {
	private ApplicationContext context;

	public Object serviceCall(String className, String methodName, Class<?>[] parameterTypes, Object[] args) {
		try {
			Class<?> serviceClass = Class.forName(className);
			//从IOC容器中获取服务对象
			Object serviceObj = context.getBean(serviceClass);
			Method method = serviceClass.getMethod(methodName, parameterTypes);
			if (serviceObj == null || method == null) {
				return null;
			}
			//通过反射调用服务获取结果
			Object result = method.invoke(serviceObj, args);
			return result;
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

}
